<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import gdglService from '@/api/gdgl'
import type { FormInstance, FormRules } from 'element-plus'
import { AjtgjlAddInputDTO } from '@/api/gdgl-dto'
import { getFldm } from '@/utils/get-fldm'
const emit = defineEmits(['refresh'])

// 获取ref
const ruleFormRef = ref()
const checkboxRef = ref()
// 入参

const ruleForm = reactive<AjtgjlAddInputDTO>({
  ajlxdm: [],
  ajlxmc: [],
  ajxxList: [],
  tglxdm: '',
  tglxmc: '',
  tgyy: '',
})

const rules = reactive<FormRules<AjtgjlAddInputDTO>>({
  tglxdm: [{ required: true, message: '请选择退改类型', trigger: 'change' }],
  ajlxdm: [
    {
      required: true,
      message: '请选择案卷类型',
      trigger: 'change',
    },
  ],
  tgyy: [
    {
      required: true,
      message: '请输入退改理由',
      trigger: 'blur',
    },
  ],
})

const tglxList = computed(() =>
  originTglxList.value.map((lx) => {
    if (lx.dm === 'gd0040001') {
      return {
        ...lx,
      }
    } else {
      return {
        ...lx,
        disabled: ajdh.value,
      }
    }
  }),
)

onMounted(() => {
  getAjlxList()
  getTglxList()
})
const originTglxList = ref<any[]>([])
const getTglxList = async () => {
  originTglxList.value = await getFldm('gd004')
}

const ajlxList = ref<any[]>([])
const getAjlxList = async () => {
  ajlxList.value = await getFldm('gd010')
}

/*
 * 打开弹框
 */
const ajxxParamsList = ref()
const ajdh = ref(false)
const dialogVisible = ref(false)
const editing = ref(false)
const openDialog = (data: any, edit?: boolean) => {
  ajdh.value = data.dh ? true : false
  ajxxParamsList.value = [data]
  dialogVisible.value = true
  if (edit) {
    editing.value = true
    Object.assign(ruleForm, data)
    ruleForm.ajlxdm = data.ajlxdm?.split(',')
    ruleForm.ajlxmc = data.ajlxmc?.split(',')
  }
}

// 退改类型改变触发
const radioChange = (val: any) => {
  let obj: any = {}
  obj = tglxList.value.find((item: any) => {
    return item.dm === val //筛选出匹配数据，这里的value是你遍历数组每一项的value，如果没有对后台返回的数据做处理，一般为id
  })
  ruleForm.tglxdm = obj.dm
  ruleForm.tglxmc = obj.mc
}

// 案卷类型改变触发
const checkboxChange = (val: any) => {
  if (val.includes('gd0100002')) {
    val.push('gd0100001')
  }
  const newArr = ajlxList.value
    .filter((item) => val.includes(item.dm))
    .map((option) => {
      return {
        label: option.mc,
        value: option.dm,
      }
    })
  ruleForm.ajlxdm = newArr.map((item) => item.value)
  ruleForm.ajlxmc = newArr.map((item) => item.label)
}

/*
 * 保存数据
 */
const saveData = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (editing.value) {
        const params = {
          ajlxdm: ruleForm.ajlxdm?.join(','),
          ajlxmc: ruleForm.ajlxmc?.join(','),
          gdjlbh: ajxxParamsList.value[0].gdjlbh,
          jlbh: ajxxParamsList.value[0].jlbh,
          tglxdm: ruleForm.tglxdm,
          tglxmc: ruleForm.tglxmc,
          tgyy: ruleForm.tgyy,
        }
        gdglService
          .updateAjtgjl(params)
          .then(() => {
            ElMessage({ type: 'success', message: '修改成功' })
            emit('refresh')
            dialogVisible.value = false
          })
          .catch((err) => {
            !err.isError && ElMessage({ type: 'warning', message: err.message })
          })
        return
      }
      const params = {
        ajlxdm: ruleForm.ajlxdm.join(','),
        ajlxmc: ruleForm.ajlxmc.join(','),
        ajxxList: ajxxParamsList.value.map((item: any) => {
          return {
            ajbh: item.ajbh,
            bmsah: item.bmsah,
            gdjlbh: item.gdjlbh,
          }
        }),
        tglxdm: ruleForm.tglxdm,
        tglxmc: ruleForm.tglxmc,
        tgyy: ruleForm.tgyy,
      }
      gdglService
        .addAjtgjl(params)
        .then(() => {
          ElMessage({ type: 'success', message: '新增案卷退改成功' })
          emit('refresh')
          dialogVisible.value = false
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 关闭弹窗
const handleClose = () => {
  ruleFormRef.value.resetFields()
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="案卷退改"
    width="40%"
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <div class="dialog-form">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="退改类型" prop="tglxdm">
          <el-radio-group v-model="ruleForm.tglxdm" ref="radioRef" @change="radioChange">
            <el-radio
              v-for="item in tglxList"
              :key="item.dm"
              :value="item.dm"
              :label="item.mc"
              :disabled="item.disabled"
            ></el-radio>
          </el-radio-group>
          <el-popover
            v-if="ajdh"
            placement="right"
            trigger="hover"
            width="210"
            content="生成档号后不允许修改和删除"
          >
            <template #reference>
              <el-icon style="margin-left: 8px"><QuestionFilled /></el-icon>
            </template>
            <div>生成档号后不允许修改和删除</div>
          </el-popover>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.tglxdm && ruleForm.tglxdm !== 'gd0040001'"
          label="案卷类型"
          prop="ajlxdm"
        >
          <el-checkbox-group v-model="ruleForm.ajlxdm" ref="checkboxRef" @change="checkboxChange">
            <el-checkbox
              v-for="item in ajlxList"
              :key="item.dm"
              :value="item.dm"
              :label="item.mc"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="退改理由" prop="tgyy">
          <el-input v-model="ruleForm.tgyy" type="textarea" :rows="4" />
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> Create </el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item> -->
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" style="margin-left: 10px" @click="saveData(ruleFormRef)"
          >确 定</el-button
        >
        <el-button type="default" style="margin-left: 10px" @click="dialogVisible = false"
          >取 消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped></style>
